package com.example.xxtautosignjava.httpclient;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Log4j
public class httpclitentest {
    private BasicCookieStore store;
    private String activeId;
    String cookie = "lv=1; fid=851; _uid=105938270; UID=105938270; vc=33FEB5E627B7E3D98365ACE0863E2F17; vc2=86814CDF743348F9C3BC7AD724956B96; xxtenc=726792cd282a34c17a122fa259a6c094; k8s=dff69c8af800cd6511cb75ac00071c19e04d42be; jrose=24A2CDE41329D8F048A077F3195576A1.mooc-2995434568-6dpsh; route=5052ecf6e7d4195bf80fb406c3095b7d; uf=5d3a3b6893c99a746dbe60b155635e2dc0144dc687ed0c954711fb246feff1f2203132374cdd535ddeeef44cfb61844dc49d67c0c30ca5047c5a963e85f11099024812edfde336c0fd68be96b6183b1a501cc1e7451ba9d00b0596cebf2a80c87f4c9b059dad24af; _d=1661333812680; vc3=IHhiQdy79TybbdCnGd8QS08o%2FotURSeGvBu5UyiNv5IIj%2FJnn8MwWGIg7ux6u9tcbQGujcoz6Lszq%2FJH7NUfV%2FrO%2F346Q5e5YloOML16%2BxkQT2Eofh8NMY2uf7dHR8Qs37DBu7hfHCWpbKNTalBzqnelEZls4gske49shR3ne%2BI%3D72223937d39b5fd0ec5ea2448b539270; DSSTASH_LOG=C_38-UN_1768-US_105938270-T_1661333812682";



    public HashMap<String, String> convertCookie(String cookie) {
        HashMap<String, String> cookiesMap = new HashMap<String, String>();
        String[] items = cookie.trim().split(";");
        for (String item : items) cookiesMap.put(item.split("=")[0], item.split("=")[1]);
        return cookiesMap;
    }

    public HashMap<String, String> convertCookieStore(BasicCookieStore store) {
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < store.getCookies().size(); i++) {
            map.put(store.getCookies().get(i).getName(), store.getCookies().get(i).getValue());
        }
        System.out.println(map);
        return map;
    }

    @Test
    public void run() throws IOException, URISyntaxException {
//        getlogin();
        posttest();

    }

    @Test
    public void addrSign() throws IOException, URISyntaxException {
        jsoupTest();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(store)//设置Cookie
                .build();
        URI uri = new URIBuilder("https://mobilelearn.chaoxing.com/pptSign/stuSignajax")
//                    .setParameter("courseId",courses.get(i).getCourse_id())
//                    .setParameter("jclassId",courses.get(i).getClass_id())
                .setParameter("activeId", "495136229")
                .setParameter("name","")
                .setParameter("address","中国")
                .setParameter("uid","")
                .setParameter("clientip","0.0.0.0")
                .setParameter("latitude","31.228518")
                .setParameter("longitude","longitude")
                .setParameter("fid","")
                .setParameter("appType","15")
                .setParameter("ifTiJiao","1")
                .build();
        HttpGet httpGet=new HttpGet(uri);
        httpGet.addHeader("Accept-Encoding","gzip, deflate");
        httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.9");
        httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36");
        // 发送请求,获取响应结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("返回值：" + content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }

    @Test
    public void  getActive_id() throws URISyntaxException, IOException {
        jsoupTest();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(store)//设置Cookie
                .build();
        //todo 遍历链表 多课程获取
        URI uri = new URIBuilder("https://mobilelearn.chaoxing.com/widget/pcpick/stu/index")
//                    .setParameter("courseId",courses.get(i).getCourse_id())
//                    .setParameter("jclassId",courses.get(i).getClass_id())
                .setParameter("courseId", "213911510")
                .setParameter("jclassId", "30541317")
                .build();

        HttpGet httpGet = new HttpGet(uri);

        CloseableHttpResponse response = httpclient.execute(httpGet);

        ArrayList<String> activeIdList=new ArrayList<>();

        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            Document doc = Jsoup.parse(content);

//            doc.getElementsByClass("Mct");
            int i=0;
            Elements startList =doc.select("#startList");
            for (Element node : startList.select(".Mct")) {
                System.out.println(i++);
                System.out.println(node);
                node.getElementsByClass("Mct").attr("onclick");
                String activeId=node.getElementsByClass("Mct").attr("onclick").substring(13,22);
                System.out.println(activeId);
                activeIdList.add(activeId);
            }
            System.out.println(activeIdList);

        }



    }


    @Test
    public void getActiveId() throws URISyntaxException, IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        URI uri = new URIBuilder("https://passport2.chaoxing.com/api/login").setParameter("name", "19854810175").setParameter("pwd", "zxcasd").build();
        HttpGet httpGet = new HttpGet(String.valueOf(uri));
        // 发送请求,获取响应结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据

                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("返回值：" + content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }

    @Test
    public void getlogin() throws IOException, URISyntaxException {
        this.store = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(store).build();


        URI uri = new URIBuilder("https://passport2.chaoxing.com/api/login").setParameter("name", "19854810175").setParameter("pwd", "zxcasd").build();
        HttpGet httpGet = new HttpGet(String.valueOf(uri));

        // 发送请求,获取响应结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据

                String content = EntityUtils.toString(response.getEntity(), "UTF-8");

                //读取cookie信息
                List<Cookie> cookielist = store.getCookies();

                for (Cookie cookie : cookielist) {
                    String name = cookie.getName();
                    String value = cookie.getValue();
                    System.out.print("cookie name =" + name);
                    System.out.print("Cookie value=" + value);
                    System.out.println();
                }
                convertCookieStore(store);
                System.out.println(convertCookie(cookie));
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }


    }

    @Test
    public void jsoupTest() throws IOException, URISyntaxException {
        getlogin();
        //获取响应
        HashMap<String, String> cookiesMap = convertCookie(cookie);
        System.out.println(cookiesMap);

        Connection.Response response = Jsoup.connect("https://mooc1-2.chaoxing.com/visit/courselistdata?courseType=1&courseFolderId=0&courseFolderSize=0").cookies(convertCookieStore(store)).method(Connection.Method.GET).execute();

        URL url = response.url();

        //获取请求的URL
        System.out.println("请求的URL为:" + url);
        //获取响应状态码
        int statusCode = response.statusCode();
        System.out.println("响应状态码为:" + statusCode);
        //获取响应数据类型
        String contentType = response.contentType();
        System.out.println("响应类型为:" + contentType);
        //获取响应信息
        String statusMessage = response.statusMessage();
        System.out.println("响应信息为:" + statusMessage);
        //判断响应状态码是否为200
        ArrayList<Course> courses = new ArrayList<>();
        if (statusCode == 200) {
            //通过这种方式可以获得响应的HTML文件
            String html = new String(response.bodyAsBytes(), "utf8");
            //获取html内容，但对应的是Document类型
            Document document = response.parse();
            //这里html和document数据是一样的，但document是经过格式化的
//            System.out.println(document);

            for (Element node : document.select("li")) {
                Course course = new Course();
//                System.out.println(node.getElementsByClass("course clearfix"));
//                System.out.println(node.getElementsByClass("course-info"));
//                System.out.println(node.getElementsByClass("course clearfix").attr("courseid"));
//
//                System.out.println(node.getElementsByClass("course clearfix").attr("clazzid"));
//                System.out.println(node.getElementsByClass("course-name overHidden2").attr("title"));
//                System.out.println("--------------------");


                String flag = node.getElementsByClass("course clearfix").attr("courseid");
                if (flag != "") {
                    course.setCourse_id(node.getElementsByClass("course clearfix").attr("courseid"));

                    course.setClass_id(node.getElementsByClass("course clearfix").attr("clazzid"));

                    course.setClass_name(node.getElementsByClass("course-name overHidden2").attr("title"));


                    courses.add(course);


                }
            }


        }
        System.out.println(courses);


    }

    @Test
    public void posttest() throws IOException {
        // 获取HttpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        TypeVo typeVo = new TypeVo();
        typeVo.setCourseType(1);
        typeVo.setCourseFolderId(0);
        typeVo.setCourseFolderSize(0);
        // json转换工具
        ObjectMapper om = new ObjectMapper();
        StringEntity entity = new StringEntity("xml");

        HttpPost httpPost = new HttpPost("https://mooc1-2.chaoxing.com/visit/courselistdata");
        httpPost.setEntity(entity);

        // 设置请求头
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        httpClient.execute(httpPost);


//        print(httpClient, httpPost);

    }

}
